package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"time"

	"github.com/hashicorp/mdns"
)


func main() {
	// 获取设备ID
	deviceID, err := getDeviceID()
	if err != nil {
		fmt.Println("Error getting device ID:", err)
		return
	}

	hostname, err := getDeviceName()
	info := []string{hostname}

	if err != nil {
		fmt.Println("Error getDeviceName:", err)
		return
	}

	// 创建一个新的 mDNS 服务器实例

	service, _ := mdns.NewMDNSService(deviceID, "_myservice._tcp", "", "", 8000, nil, info)


	server, _ := mdns.NewServer(&mdns.Config{Zone: service})
	defer server.Shutdown()


	for {
		select {
		case <-time.After(10 * time.Second):

			entriesCh := make(chan *mdns.ServiceEntry, 8)
			go func() {
				for entry := range entriesCh {
					fmt.Printf("边缘网关发现其他节点: %v\n", entry)
				}
			}()
							
			// Start the lookup
			mdns.Lookup("_myservice._tcp", entriesCh)
		
			
			close(entriesCh)

		case <-time.After(time.Second * 120):
			log.Println("重置时间 应该不会触发")
			return
		}
	}
	
}

// 获取设备名称
func getDeviceName() (string, error) {
	out, err := exec.Command("hostname").Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}

// 获取设备ID
func getDeviceID() (string, error) {
	switch runtime.GOOS {
	case "windows":
		out, err := exec.Command("wmic", "csproduct", "get", "uuid").Output()
		if err != nil {
			return "", err
		}
		// Windows 的输出需要进行一些格式化处理
		output := strings.TrimSpace(string(out))
		lines := strings.Split(output, "\n")
		if len(lines) > 1 {
			return strings.TrimSpace(lines[1]), nil
		}
		return "", nil // 或者返回一个错误

	case "linux":
		bytes, err := os.ReadFile("/etc/machine-id")
		if err != nil {
			return "", err
		}
		return strings.TrimSpace(string(bytes)), nil

	default:
		return "", nil // 或者返回一个错误，表示不支持的操作系统
	}
}

